<?php
/**
 * Created by PhpStorm.
 * User: gakuin
 * Date: 16/8/28
 * Time: 上午10:11
 */
namespace app\controllers;

use app\models\Commodity;
use app\models\Collection;
use app\models\Attr;
use app\models\Attr_opt;
use yii\web\Controller;

class CommodityDetailController extends Controller
{
    public $layout='detail';
    public function actionDetail()
    {
        $request = \Yii::$app->request;
        $commodity_id = $request->get('commodity_id');
        $share_id = $request->get('share_id');


        if (!$commodity_id)
            $commodity_id = 1;
        $commdityModel = new Commodity();
        $commodityDetail = $commdityModel->getCommodity($commodity_id); //商品信息
        $collection = new Collection();
        $collection_id = $collection->getCollectionId($commodity_id);
        $collection_flag = $collection->getCollectionDeleteFlag($commodity_id);

        $commodityAttributesModel = new Attr();  //商品规格('颜色','尺寸'等)
        $commodityAttributes = json_decode($commodityDetail['attr_opt_id'], true);
        if (!$commodityAttributes) {
            $commodityAttributes = json_decode('[["22",["22"]],["19",["18"]],["18",["25"]]]', true);
        }
        //解析数据并且转换数据格式.
        $commodityAttributeArray = array();
        for ($i = 0; $i < count($commodityAttributes); $i++) {
            $attr_id = $commodityAttributes[$i][0];
            $attr_opt_ids = $commodityAttributes[$i][1];
            $attr = $commodityAttributesModel->getCommodityAttributes($attr_id);//规格
            if($attr){
                $tempArray1 = array();
                $tempArray1['attr_name'] = $attr['attr_name'];
                $commodityAttributeOptionsModel = new Attr_opt();
                $commodityAttributeOptions = $commodityAttributeOptionsModel->getCommodityAttributeOptions($attr_opt_ids);//具体规格
                $tempArray1['attr_opts'] = array();
                foreach ($commodityAttributeOptions as $commodityAttributeOption) {
                    $tempArray2 = array();      //临时数组,用于存放attr_opt_id\attr_opt_name
                    $tempArray2['attr_opt_id'] = $commodityAttributeOption['attr_opt_id'];
                    $tempArray2['attr_opt_name'] = $commodityAttributeOption['attr_opt_name'];
                    array_push($tempArray1['attr_opts'], $tempArray2);
                }
                array_push($commodityAttributeArray, $tempArray1); //最终所需要的数据结构.
            }
        }
        return $this->render('detail', ['commodityDetail' => $commodityDetail, 'commodityAttributeArray' => $commodityAttributeArray, 'share_id' => $share_id,'collection_id'=>$collection_id,'collection_flag'=>$collection_flag]);
    }
}